#include<stdio.h>
#include<Viewer_Interpreter/Viewer_OpenGL_Interpreter.h>

#include<tool/viewer_tools.h>
#include<Arcroll.h>
#include<Mesh_IO/Mesh_IO.h>
#include<tool/libcell_tools_formats.h>
#include<tool/libcell_tools_view.h>
#include<Mesh/libcell_iterator.h>
#include<Mesh/Mesh_Operator.h>
#include "export_obj.h"
#include "directories_and_files.h"

#include<macros.h>

static inline int is_point_in_quad(double* p,double**quad)
{
   if(p[0]<quad[0][0]-1e-6||p[0]>quad[1][0]+1e-6||p[1]<quad[0][1]-1e-6||p[1]>quad[1][1]+1e-6)
   {
        return 0;
   } 
   return 1;

}
 
void my_test(char* path,double**quad)
{
    int count_files=0;
    char** files=search_dir_files(path,&count_files);
    for(int i=0;i<count_files;i++)
    {
        int temp_len=strlen(files[i]);
        if(temp_len>4&&files[i][temp_len-1]=='j'&&files[i][temp_len-2]=='b'&&files[i][temp_len-3]=='o'&&files[i][temp_len-4]=='.') 
        {
            char file[200]={0};
            strcat(file,path);
            strcat(file,"/");
            strcat(file,files[i]);

            printf("%s\n",file); 
            Mesh mesh;
            Mesh_init(&mesh);
            _ReadObj_(&mesh,file);
            OBJ_MESH_PROP* omp=(OBJ_MESH_PROP*)(mesh.prop);
            char outfile[200]={0};
            strcat(outfile,path);
            strcat(outfile,"/");
            strncat(outfile,files[i],temp_len-4);
            strcat(outfile,"n.obj");
            printf("outfile,%s\n",outfile);     
            Node* node=NULL;
            for(auto cit=mesh.c_begin(&mesh);cit!=mesh.c_end(&mesh);cit++)
            {
                if(is_point_in_quad(quote(cit)->vertices[0]->point,quad)&&is_point_in_quad(quote(cit)->vertices[1]->point,quad)
                    &&is_point_in_quad(quote(cit)->vertices[2]->point,quad))
                {
                    node=node_overlying(node,quote(cit));
                }
            }

            export_obj_from_node(node,file,omp->mtlname); 
            if(node==NULL)
            {
                remove(file);
            }
            free_node(node);

            for(auto cit=mesh.c_begin(&mesh);cit!=mesh.c_end(&mesh);cit++)
            {
                SAFE_FREE(quote(cit)->prop);
            }

            Mesh_free(&mesh);
            SAFE_FREE(mesh.prop);
        }
    } 
    for(int i=0;i<count_files;i++)
    {
        free(files[i]);
    }
    free(files);
}

int main()
{
    double* boundaries[2]={NULL};
    boundaries[0]=(double*)malloc(sizeof(double)*3);
    boundaries[1]=(double*)malloc(sizeof(double)*3);
    //A2.txt
    boundaries[0][0]=-10.33344941;boundaries[0][1]=16.97317423;
    boundaries[1][0]=399.21541005;boundaries[1][1]=284.95248341;
//A1.txt
    // boundaries[0][0]=-19.26078697;boundaries[0][1]=-103.92687376;
    // boundaries[1][0]=387.71741855;boundaries[1][1]=140.29763709;

    my_test("/home/libo/Documents/c/lmeshlab/A2-0914-aligned",boundaries);

    printf("end\n");
    return 0;
}